//
//  WSFavourViewController.m
//  GroupFourFM
//
//  Created by 王鑫 on 15/12/22.
//  Copyright © 2015年 GroupFour. All rights reserved.
//

#import "WSFavourViewController.h"
#import "WSAlbumsDetailViewController.h"
#import "WSFavourTableViewCell.h"
#import "WSFavourModel.h"
#import <BmobSDK/Bmob.h>


@interface WSFavourViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic,retain)WSBaseTableView *favorTableView;
@property(nonatomic,retain)NSMutableArray *recommendArray;
@property(nonatomic,retain)NSMutableArray *myAlbumArray;

@property (nonatomic, assign) BOOL isUpLoad;
@end

@implementation WSFavourViewController


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTranslucent:NO];
#pragma mark - 查询收藏
    
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Collect_album"];
    //查找GameScore表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (self.isUpLoad == NO){
            
            [self.myAlbumArray removeAllObjects];
        }
        for (BmobObject *obj in array) {
            
            WSFavourModel *mode = [[WSFavourModel alloc] init];
            mode.coverMiddle = [obj objectForKey:@"albumPic"];
            mode.intro = [obj objectForKey:@"albumintro"];
            mode.title = [obj objectForKey:@"albumName"];
            mode.tracks = [obj objectForKey:@"albumtracks"];
            mode.albumId = [obj objectForKey:@"albumId"];
            mode.objectID = [obj objectId];
            [self.myAlbumArray addObject:mode];
        }
        
        
    }];

    [self.favorTableView.mj_header beginRefreshing];
    [self.favorTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.myAlbumArray = [NSMutableArray array];
    self.recommendArray = [NSMutableArray array];
    [self createTableView];
    [self getData];

    self.isUpLoad = YES;
    //self.favorTableView.backgroundColor = [UIColor whiteColor];
}

#pragma mark - 创建tableview
- (void)createTableView
{
    self.favorTableView = [[WSBaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT_TABLE) style:UITableViewStyleGrouped];
    [self.view addSubview:self.favorTableView];
    
    self.favorTableView.dataSource = self;
    self.favorTableView.delegate = self;
        
    [self.favorTableView registerClass:[WSFavourTableViewCell class] forCellReuseIdentifier:@"WSFavourTableViewCell"];
    [self.favorTableView reloadData];
    self.favorTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.favorTableView.rowHeight = SCREEN_WIDTH*0.3;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    self.favorTableView.mj_header = header;
    //[self.favorTableView.mj_header beginRefreshing];
    
}

#pragma mark - 设置几个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

#pragma mark - 设置每个区有几个人row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.myAlbumArray.count;
    }
    else
    {
        return self.recommendArray.count;
    }
}

#pragma mark - 设置cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WSFavourTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WSFavourTableViewCell"];
    
    
    if (indexPath.section == 0) {
        WSFavourModel *model = [self.myAlbumArray objectAtIndex:indexPath.row];
        cell.model = model;
        cell.nextBtn.tag = indexPath.row;
        
        [cell.nextBtn setImage:[UIImage imageNamed:@"cell_delete_n@2x.png"] forState:UIControlStateNormal];
        [cell.nextBtn setImage:[UIImage imageNamed:@"cell_delete_h"] forState:UIControlStateHighlighted];
        [cell.nextBtn addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    if (indexPath.section == 1) {
        WSFavourModel *model = [self.recommendArray objectAtIndex:indexPath.row];
        cell.model = model;
        [cell.nextBtn setImage:[UIImage imageNamed:@"cell_arrow@2x.png"] forState:UIControlStateNormal];
        [cell.nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
        
    }

    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.1;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return @"推荐收藏";
    }
    return @"我收藏的专辑";
}

#pragma mark - 请求数据
- (void)getData
{
    
    self.isUpLoad = NO;
    NSString *urlStr = @"http://mobile.ximalaya.com/mobile/album/recommend/list/unlogin?device=iphone";
    [WSAppTools getDataWithURL:urlStr block:^(id result) {
        
        //        NSLog(@"%@", result);
        NSMutableArray *dataArray = [result objectForKey:@"frDatas"];
        //        NSLog(@"%@", dataArray);
        
        for (NSMutableDictionary *dic in dataArray) {
            WSFavourModel *model = [WSFavourModel modelWithDictionary:dic];
            [self.recommendArray addObject:model];
            
        }
        
        
        //        NSLog(@"%@", self.recommendArray);
        [self.favorTableView reloadData];
        [self.favorTableView.mj_header endRefreshing];

        
    } error:^(NSError *error) {
        
        NSLog(@"请求失败  error");
    }];

}

#pragma mark - 删除按钮方法
-(void)deleteAction:(UIButton *)btn
{
    UIAlertController *alterC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认要删除此专辑?!" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alterC animated:YES completion:^{
        
        
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        WSFavourModel *favour = self.myAlbumArray[btn.tag];
        
        BmobQuery *bquery = [BmobQuery queryWithClassName:@"Collect_album"];
        [bquery getObjectInBackgroundWithId:favour.objectID block:^(BmobObject *object, NSError *error){
            if (error) {
                //进行错误处理
                NSLog(@"删除失败");

            }
            else{
                if (object) {
                    //异步删除object
                    [object deleteInBackground];
                    NSLog(@"删除成功");
                }
            }
        }];
       
        [self.myAlbumArray removeObject:favour];
       
        [self.favorTableView reloadData];
    }];
    
    UIAlertAction *channelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [alterC addAction:channelAction];
    [alterC addAction:sureAction];
}

-(void)nextAction
{
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        
        WSAlbumsDetailViewController *albumsDetailVC = [[WSAlbumsDetailViewController alloc] init];
        [(WSTabBarController *)self.tabBarController isHiddenTabBar:YES withViewController:albumsDetailVC];
        
        albumsDetailVC.albumId = ((WSFavourModel *)self.myAlbumArray[indexPath.row]).albumId;
        
        [self.navigationController pushViewController:albumsDetailVC animated:YES];
    }
    else if (indexPath.section == 1){
        WSAlbumsDetailViewController *albumsDetailVC = [[WSAlbumsDetailViewController alloc] init];
        [(WSTabBarController *)self.tabBarController isHiddenTabBar:YES withViewController:albumsDetailVC];
        
        albumsDetailVC.albumId = ((WSFavourModel *)self.recommendArray[indexPath.row]).albumId;
        albumsDetailVC.myTitle = ((WSFavourModel *)self.recommendArray[indexPath.row]).albumTitle;
        [self.navigationController pushViewController:albumsDetailVC animated:YES];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
